package com.pkk.penguin.frame.know.java.Javacoreknowledge.volatiles;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import org.junit.Test;

/**
 * @description: volatile的简单使用
 * @author: peikunkun
 * @create: 2020-01-13 11:36
 **/
public class VolatileSimple {

  private int i = 10;


  //同一时刻,只有一个线程修改此值
  private volatile int j = 10;


  @Test
  @SuppressWarnings({"all"})
  public void Administrator_15_20200113113921() throws InterruptedException {
    System.out.println("欢迎使用单元测试方法【Administrator_15()_20200113113921】");
    System.out.println("此方法测试描述：【暂时没有模拟】");

    int threadNum = 2;
    CyclicBarrier cyclicBarrier = new CyclicBarrier(threadNum);

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          i = 11;
          j = 11;
          System.out.println(Thread.currentThread().getName() + "-i:" + i + "-j:" + j);
          Thread.sleep(10);
          System.out.println(Thread.currentThread().getName() + "-i:" + i + "-j:" + j);
          //线程进入阻塞【barrier】状态
          cyclicBarrier.await();
          System.out.println(Thread.currentThread().getName() + "-i:" + i + "-j:" + j);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (BrokenBarrierException e) {
          e.printStackTrace();
        }
      }
    }).start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(5);
          i = 12;
          j = 12;
          System.out.println(Thread.currentThread().getName() + "-i:" + i + "-j:" + j);
          //线程进入阻塞【barrier】状态
          cyclicBarrier.await();
          System.out.println(Thread.currentThread().getName() + "-i:" + i + "-j:" + j);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (BrokenBarrierException e) {
          e.printStackTrace();
        }
      }
    }).start();
    Thread.sleep(1000L);
    System.out.println(Thread.currentThread().getName() + "-i:" + i + "-j:" + j);
  }


}
